package com.shixi.shixitraining.shixitraining.ui.tabhome.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ZoomButtonsController;

import com.shixi.shixitraining.shixitraining.R;
import com.shixi.shixitraining.shixitraining.base.BaseActivity;
import com.shixi.shixitraining.shixitraining.http.CallbackImple;
import com.shixi.shixitraining.shixitraining.http.HttpUtil;
import com.shixi.shixitraining.shixitraining.ui.tabhome.entity.MyCollectBean;
import com.shixi.shixitraining.shixitraining.ui.tabhome.entity.OverseasDetailBean;
import com.shixi.shixitraining.shixitraining.util.ToastUtil;
import com.shixi.shixitraining.shixitraining.util.UserManager;
import com.shixi.shixitraining.shixitraining.view.recycleview.BaseAdapter;
import com.shixi.shixitraining.shixitraining.view.recycleview.BaseRecycleHolder;

import java.lang.reflect.Field;
import java.util.List;

import retrofit2.Call;

import static com.shixi.shixitraining.shixitraining.constant.Constants.ADDCOLLECT;

public class OverseasDetailActivity extends BaseActivity implements View.OnClickListener {


    private WebView webJob;
    private String id;
    private String collectionType;
    private ImageView mCollectImg;
    private TextView mCollectTv;
    private String collection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_overseas_detail);
        initView();
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();

        if (bundle != null) {
            String jobId = bundle.getString("jobId");
            initData(jobId);
        }
        initWebView();

    }

    private void initWebView() {
        webJob = (WebView) findViewById(R.id.web_job);
        String ua = webJob.getSettings().getUserAgentString();
        webJob.getSettings().setTextSize(WebSettings.TextSize.LARGEST);
        webJob.setWebViewClient(new WebListener());
        webJob.getSettings().setUserAgentString(ua + ";");
        webJob.getSettings().setJavaScriptEnabled(true);
        webJob.getSettings().setBuiltInZoomControls(true);
        webJob.getSettings().setSupportZoom(true);
        webJob.getSettings().setUseWideViewPort(true);
        webJob.getSettings().setLoadWithOverviewMode(true);


        if (Integer.parseInt(Build.VERSION.SDK) >= 11) {// 用于判断是否为Android 3.0系统,
            webJob.getSettings().setDisplayZoomControls(false);
        } else {
            setZoomControlGone(webJob);
        }

    }

    private void initData(String jobId) {

        HttpUtil.getInstance().getApiInterface().jobDetail("http://api.shixigroup.com/job/view/id/" + jobId).enqueue(new CallbackImple<OverseasDetailBean>() {
            @Override
            public void onError(Call<OverseasDetailBean> call, Throwable t) {
                ToastUtil.showShortToast(OverseasDetailActivity.this, t.getMessage());
            }

            @Override
            public void onSuccess(Call<OverseasDetailBean> call, OverseasDetailBean response) {
                if (response.getStatus() == 200) {

                    if (response.getData() != null) {
                        String address = response.getData().getAddress();
                        String amount = response.getData().getAmount();
                        String apply = response.getData().getApply();
                        String duration_id = response.getData().getDuration_id();
                        String duration_name = response.getData().getDuration_name();
                        String time = response.getData().getTime();
                        String title = response.getData().getTitle();
                        String trade_name = response.getData().getTrade_name();
                        String wages = response.getData().getWages();
                        String duty = response.getData().getDuty();
                        String requirement = response.getData().getRequirement();
                        collectionType = response.getData().getCollection_type();
                        collection = response.getData().getCollection();

                        id = response.getData().getId();

                        TextView mTitle = (TextView) findViewById(R.id.job_detail_title);
                        TextView address_tv = (TextView) findViewById(R.id.job_detail_address);
                        TextView count_tv = (TextView) findViewById(R.id.job_detail_count);
                        TextView duration_tv = (TextView) findViewById(R.id.job_detail_duration);
                        TextView nature_tv = (TextView) findViewById(R.id.job_detail_nature);
                        TextView time_tv = (TextView) findViewById(R.id.job_detail_time);
                        TextView trade_tv = (TextView) findViewById(R.id.job_detail_trade);
                        TextView wages_tv = (TextView) findViewById(R.id.job_detail_wages);
                        WebView webRequire = (WebView) findViewById(R.id.web_require);

                        mTitle.setText(title);
                        time_tv.setText(time);
                        address_tv.setText(address);
                        count_tv.setText(amount);
                        duration_tv.setText(duration_name);
                        trade_tv.setText(trade_name);
                        wages_tv.setText(wages);
//处理HTML
                        if (!TextUtils.isEmpty(response.getData().getDuty())) {
                            String string = response.getData().getDuty().replace("&lt;", "<");
                            string = string.replace("&gt;", ">").replace("&amp;", "&")
                                    .replace("&nbsp;", " ")
                                    .replace("&quot;", "\"")
                                    .replace("&apos;", "\'");

                            webJob.loadDataWithBaseURL(null, string, "text/html", "utf-8", null);
                        }
                        if (!TextUtils.isEmpty(response.getData().getRequirement())) {
                            String string = response.getData().getRequirement().replace("&lt;", "<");
                            string = string.replace("&gt;", ">").replace("&amp;", "&")
                                    .replace("&nbsp;", " ")
                                    .replace("&quot;", "\"")
                                    .replace("&apos;", "\'");
                            webRequire.loadDataWithBaseURL(null, string, "text/html", "utf-8", null);

                        }

                        if (!TextUtils.isEmpty(response.getData().getRequirement())) {

                        }
                    } else {
                        ToastUtil.showShortToast(OverseasDetailActivity.this, response.getMsg());
                    }

                } else {
                    ToastUtil.showShortToast(OverseasDetailActivity.this, "数据为空");
                }


            }
        });
    }

    // 添加收藏
    private void addCollect(String collectionType, String id) {
        String token = UserManager.getInstance().getToken();
        String userId = UserManager.getInstance().getUserId();
        String url = ADDCOLLECT+"&token="+token+"&userId="+userId+"&collection_type="+collectionType+"&id="+id;

        HttpUtil.getInstance().getApiInterface().myCollect(url).enqueue(new CallbackImple<MyCollectBean>() {
            @Override
            public void onError(Call<MyCollectBean> call, Throwable t) {
                ToastUtil.showShortToast(OverseasDetailActivity.this, t.getMessage());

            }

            @Override
            public void onSuccess(Call<MyCollectBean> call, MyCollectBean response) {
                if (response.getStatus() == 200) {

                    String data = response.getData();

                    ToastUtil.showShortToast(OverseasDetailActivity.this, response.getMsg());
                    if (collection.equals(0)){
                        mCollectImg.setImageResource(R.drawable.icon_collect);
                        mCollectTv.setText("收藏");
                    }else if (collection.equals(1)){
                        mCollectImg.setImageResource(R.drawable.icon_collect_selected);
                        mCollectTv.setText("已收藏");
                    }

                } else {
                    ToastUtil.showShortToast(OverseasDetailActivity.this, response.getMsg());
                }

            }
        });


    }


    private class WebListener extends WebViewClient {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
//            hideLoading();
        }

    }

    public void setZoomControlGone(View view) {
        Class classType;
        Field field;
        try {
            classType = WebView.class;
            field = classType.getDeclaredField("mZoomButtonsController");
            field.setAccessible(true);
            ZoomButtonsController mZoomButtonsController = new ZoomButtonsController(
                    view);
            mZoomButtonsController.getZoomControls().setVisibility(View.GONE);
            try {
                field.set(view, mZoomButtonsController);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        ImageView mBackImg = (ImageView) findViewById(R.id.iv_overseas_back);
        TextView mApply = (TextView) findViewById(R.id.tv_overseas_apply);
        LinearLayout mCollectlin = (LinearLayout) findViewById(R.id.lin_collection);
        mCollectImg = (ImageView) findViewById(R.id.iv_collection);
        mCollectTv = (TextView) findViewById(R.id.tv_collection);
        mCollectlin.setOnClickListener(this);
        mBackImg.setOnClickListener(this);
        mApply.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_overseas_back:
                this.finish();
                break;
            case R.id.tv_overseas_apply:
                Bundle bundle = new Bundle();
                bundle.putString("id", id);
                Intent intent = new Intent(this, OverseaApplyActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.lin_collection:
                addCollect(collectionType, id);
                break;
        }
    }


    private class OverseasAdapter extends BaseAdapter<OverseasDetailBean> {

        public OverseasAdapter(Context context, List<OverseasDetailBean> data) {
            super(context, data);
        }

        @Override
        public void convert(BaseRecycleHolder holder, OverseasDetailBean item, int position) {
            holder.setText(R.id.job_detail_title, item.getData().getTitle());
            holder.setText(R.id.job_detail_time, item.getData().getTime());
            holder.setText(R.id.job_detail_trade, item.getData().getTrade_name());
            holder.setText(R.id.job_detail_address, item.getData().getAddress());
            holder.setText(R.id.job_detail_count, item.getData().getAmount());
            holder.setText(R.id.job_detail_nature, item.getData().getNature_name());
            holder.setText(R.id.job_detail_duration, item.getData().getDuration_name());
            holder.setText(R.id.job_detail_wages, item.getData().getWages());
        }

        @Override
        protected int getLayoutId(int viewType) {
            return R.layout.activity_overseas_detail;
        }
    }
}
